package com.qinglei.recoup.common.runner;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.service.CacheService;
import com.qinglei.recoup.common.service.impl.ProductCache;
import com.qinglei.recoup.system.domain.User;
import com.qinglei.recoup.system.manager.UserManager;
import com.qinglei.recoup.system.pojo.PageParam;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.SystemConfigService;
import com.qinglei.recoup.system.service.TourLogService;
import com.qinglei.recoup.system.service.UserService;
import com.qinglei.recoup.system.service.impl.EventServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 缓存初始化
 */
@Slf4j
@Component
public class CacheInitRunner implements ApplicationRunner {

    @Autowired
    private UserService userService;

    @Autowired
    private CacheService cacheService;
    @Autowired
    private UserManager userManager;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private BedService bedService;
    @Resource
    private TourLogService tourLogService;

    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    private ProductCache productCache;
    @Override
    public void run(ApplicationArguments args) {
        try {
            log.info("Redis连接中 ······");
            cacheService.testConnect();

            log.info("缓存初始化 ······");
            log.info("缓存用户数据 ······");
            PageParam pageParam = new PageParam();
            IPage<User> userDetailPage = this.userService.findUserDetail(null, pageParam);
            long pages = userDetailPage.getPages();
            for (int i = 1; i <= pages; i++) {
                List<User> userList = userDetailPage.getRecords();
                for (User user : userList) {
                    userManager.loadUserRedisCache(user);
                }
            }
            //缓存用户，部门关系
//            this.userService.findSubordinatesMap().stream().forEach((map)-> {
//                try {
//                    cacheService.saveUserSubordinates(map.getDeptId(),map.getUserIds());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            });

            // 初始化系统配置
//            cacheService.saveOutBedTimeout(systemConfigService.getOutBedTimeout());
//            cacheService.saveTakeEventTimeout(systemConfigService.getTakeEventTimeout());
            systemConfigService.loadTakeEventTimeoutRedisCache();
            bedService.loadBedMonitorTimeRedisCache();
            tourLogService.loadTourTimeRedisCache();
            // 初始化字典缓存
            cacheService.saveDictItemGroup(EventServiceImpl.DICT_EVENT_FILTER_TYPE);
            cacheService.saveDictItemGroup(EventServiceImpl.DICT_REPORT_REASON);

            productCache.cacheProduct();
        } catch (Exception e) {
            log.error("缓存初始化失败，{}", e.getMessage());
            log.error(" ____   __    _   _ ");
            log.error("| |_   / /\\  | | | |");
            log.error("|_|   /_/--\\ |_| |_|__");
            log.error("                        ");
            log.error("RECOUP启动失败              ");
            if (e instanceof RedisConnectException) {
                log.error("Redis连接异常，请检查Redis连接配置并确保Redis服务已启动");
            } else {
                log.error("run error", e);
            }

            // 关闭 RECOUP
            context.close();
        }
    }
}
